import {Component, OnDestroy, OnInit} from '@angular/core';
import {PageSubject} from '../../../util/page-subject';
import {API, MsgConstants} from '../../../constants/constants';
import {TableUtil} from '../../../util/table-util';
import {ResponseUtil} from '../../../util/response-util';
import {Path} from '../../../portal/admin/admin-breadcrumb/breadcrumb';
import {DaCoranaService} from '../da-corana/da-corana.service';
import {DaCorrelationService} from './da-correlation.service';
import {MsgResult} from '../../../models/msg-result';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {DaChartColor, DaChartTitle, DaFactorColor, DaFactorName} from '../da-constants';
import {Observable} from 'rxjs/Observable';

declare var $;
declare var moment;
declare var echarts;

@Component({
  selector: 'app-da-correlation',
  templateUrl: './da-correlation.component.html',
  styleUrls: ['./da-correlation.component.css']
})
export class DaCorrelationComponent implements OnInit, OnDestroy {
  // 数据格式
  timeDataType = 'hourData';
  timeDataArr: Array<any> = [];
  // 日期选择
  startDate = new Date(moment().subtract(1, 'w').format('YYYY/MM/DD HH:00'));
  endDate =  new Date();
  // 站点
  siteCode = '';
  rangeCode = '';
  // 多选
  factorDataArr: Array<any> = [];
  checkFactor = '';
  checkFactorArr: Array<any> = [];
  checkFactorName = {};

  isLoading: any = true;

  table: any;
  tableData: Array<any> = [];
  tableHeadArr: Array<any> = [];
  siteArr: Array<any> = [];

  rangeArr: Array<any> = [
    '1.0', '0.9', '0.8', '0.7', '0.6', '0.5',
    '0.4', '0.3', '0.2', '0.1', '0.0', '-0.0', '-0.1',
    '-0.2', '-0.3', '-0.4', '-0.5', '-0.6',
    '-0.7', '-0.8', '-0.9', '-1.0'];

  rangeColorArr: Array<string> = [
    '#F8696B', '#F9766E', '#FA8370', '#FB9073', '#FB9D75', '#FCAA78',
    '#FDB77A', '#FDC47D', '#FED17F', '#FFDE82', '#FFEB84', '#FFEB84', '#EFE683',
    '#DFE282', '#D0DD81', '#C0D980', '#B1D47F', '#A1D07E',
    '#91CB7D', '#82C67C', '#72C27B', '#63BE7B'];
  /**
   * type
   */
  chartObj: any;
  resizeEnent: any;
  /**
   * 禁用日期数组
   * @type {any[]}
   */
  disabledDate: Array<any> = [];

  constructor(
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private tableUtil: TableUtil,
    private correlationService: DaCorrelationService
  ) { }

  ngOnInit() {
    this.pushPage();
    this.screenChange();
    this.initData();
    this.loadCorrelation();
    this.getSiteData();
  }
  ngOnDestroy () {
    this.destroyResize();
  }
  /**
   * 面包屑导航
   */
  pushPage() {
    const path = new Path('多因子分析', '');
    this.pageSubject.pushPage('相关性分析', '查询', path);
  }
  /**
   * 屏幕大小改变
   */
  screenChange() {
    this.resizeEnent = Observable.fromEvent(window, 'resize')
      .debounceTime(100) // 以免频繁处理
      .subscribe((event) => {
        // 这里处理页面变化时的操作
        this.chartObj.resize();
      });
  }
  /**
   * 取消监听屏幕变化
   * */
  destroyResize() {
    this.resizeEnent.unsubscribe();
  }
  /**
   * 初始化数据
   */
  initData() {
    this.timeDataArr = [{name: '小时', dataType: 'hourData'}, { name: '日', dataType: 'dayData'}, {name: '周', dataType: 'weekData'}];
    this.chartObj = echarts.init(document.getElementById('corLine'));
    this.updateFactorCheck();
  }
  /**
   * 时间类型切换
   * @param timeDataType
   */
  timeDataChange(timeDataType) {
    if (this.timeDataType === timeDataType) {
      return false;
    }
    this.timeDataType = timeDataType;
    this.changeStartAndEndDate();
    this.search();
  }

  /**
   * 日期选择
   */
  startValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.startDate = null;
    //   this.dialogService.info('开始时间大于结束时间')
    // }
  };
  endValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.endDate = null;
    //   this.dialogService.info('结束时间小于开始时间')
    // }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= startValue.getTime()  && startValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime() || !isInRange;
    } else {
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startDateTime =  new Date(moment(this.startDate).format('YYYY/MM/DD')).getTime();
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= endValue.getTime()  && endValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime || !isInRange;
    } else {
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime;
    }
  };
  get showTimeParams() {
    if (this.timeDataType === 'hourData') {
      return {
        nzFormat: 'HH'
      }
    } else {
      return false;
    }
  }

  /**
   * 下拉多选
   */
  updateAllChecked = (data) => {
    data.indeterminate = false;
    if (data.allChecked) {
      data.factor.forEach(item => item.checked = true);
    } else {
      data.factor.forEach(item => item.checked = false);
    }
    this.updateFactorCheck();
  };
  updateSingleChecked = (data, loc?: any) => {
    if (loc) {
      data.factor[loc.index].checked = false;
      // this.isShowDropMenu = true;
    }
    if (data.factor.every(item => item.checked === false)) {
      data.allChecked = false;
      data.indeterminate = false;
    } else if (data.factor.every(item => item.checked === true)) {
      data.allChecked = true;
      data.indeterminate = false;
    } else {
      data.indeterminate = true;
    }
    this.updateFactorCheck();
  };
  updateFactorCheck () {
    const checkFactorArr = [];
    this.checkFactorArr = [];
    this.factorDataArr.forEach((factorData) => {
      factorData.factor.forEach((factor) => {
        if (factor.checked) {
          checkFactorArr.push(factor.value);
          this.checkFactorName[factor.value] = factor.label;
          // + '(' + factor.name + ')'
          this.checkFactorArr.push(factor.value);
        }
      })
    });
    this.checkFactor = checkFactorArr.splice(0, 3).join(',');
  }

  /**
   * 添加表格中的列数据
   */
  addColumns = () => {
    const colArr = [];
    const classfi = {
      field: 'type',
      title: '类别',
      valign: 'middle',
      halign: 'center',
      width: 80
    };
    colArr.push(classfi);
    this.tableHeadArr.forEach((val, i) => {
      colArr.push({
        field: val.code,
        title: val.name,
        class: 'allColor',
        valign: 'middle',
        halign: 'center',
        width: 100,
        formatter: this.formatColor
      })
    });
    return colArr;
  };

  /**
   * 查询
   */
  search () {
    if (this.startDate > this.endDate) {
      this.dialogService.info('开始时间大于结束时间，请重新选择');
    } else {
      this.isLoading = true;
      this.getCorreData();
      this.getCorreLineData();
    }
  }
  loadCorrelation() {
    this.table = this.tableUtil.load('one_table_correlation',  {
      columns: this.addColumns(),
      idField: 'id',
      sidePagination: 'server',
      pagination: false,
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_correlation',
      data: this.tableData,
      // url: API.dPageListV2,
      // method: 'post',
      // //传递附加参数
      // queryParams: (params) => {
      //   params.code = $('#dicCode').val();
      //   params.display = $('#dicDisplay').val();
      //   params.isUse = $('#isUse').val();
      //   params.pId =  $('#dicId').val();
      //   return params;
      // },
      // //返回数据处理器
      // responseHandler: (result) => {
      //   return this.responseUtil.bsPageHandler(result, (result) => {
      //   });
      // },
      // height: 700,//table高度
      sortable: true,
      order: 'asc',
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true // 响应式
    });
  }

  /**
   * 格式化数据
   * @param value
   * @param row
   * @param index
   * @returns {string}
   */
  formatColor = (value, row, index) => {
    return '<div style="border-radius:2px;padding: 8px;background: ' + this.aqiColor(value) + ';"> ' + (value || '-') + '</div>'
  };
  /**
   * 等级颜色
   * @param data
   * @returns {string}
   */
  aqiColor = (data) => {
    let num: any = parseFloat(data);
    num = num.toFixed(1);
    const index = this.rangeArr.indexOf(num);
    if (index === -1) {
      return '#fff';
    }
    return this.rangeColorArr[index];
  };
  /**
   * 获取站点数据
   */
  getSiteData = () => {
    this.correlationService.getSiteData().subscribe(
      result => this.responseUtil.success(result, this.progressD),
      error => this.responseUtil.error(error)
    )
  };
  progressD = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.siteArr = result.data;
        this.siteCode = this.siteArr[0].SITECODE;
        this.rangeCode = this.siteArr[0].RANGECODE;
        this.changeSite(false);
        this.getPmComData();
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  changeSite = (isOpen) => {
    if (!isOpen) {
      if (this.rangeCode) {
        this.disabledDate = [];
        let site;
        this.siteArr.every((val) => {
          if (val.RANGECODE === this.rangeCode) {
            this.siteCode = val.SITECODE;
            site = val;
            return false
          } else {
            return true
          }
        });
        if (site.DATESTR && typeof site.DATESTR === 'string' ) {
          const dateArr = site.DATESTR.split(';');
          if (dateArr.length > 0) {
            dateArr.forEach((val) => {
              const singleDateArr = val.split(',');
              this.disabledDate.push({startDate: singleDateArr[0], endDate: singleDateArr[1]})
            });
            this.changeStartAndEndDate();
          }
        }
      } else {
        this.disabledDate = [];
      }
    }
  };
  /**
   * 修改开始结束时间
   */
  changeStartAndEndDate = () => {
    if (this.disabledDate.length > 0) {
      const dateLength = this.disabledDate.length;
      const dateObj = this.disabledDate[dateLength - 1];
      const startTime = new Date(moment(dateObj.startDate).format('YYYY/MM/DD 00:00:00'));
      const endTime = new Date(moment(dateObj.endDate).format('YYYY/MM/DD 00:00:00'));
      const nowDate =  new Date(moment().format('YYYY/MM/DD 00:00:00'));
      const nowDateIsInRange = startTime.getTime() < nowDate.getTime()  && nowDate.getTime() <= endTime.getTime();
      if (nowDateIsInRange) {
        this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        let startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          startDate = new Date(moment().subtract('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          startDate = new Date(moment().subtract('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          startDate = new Date(moment().subtract('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        const startDateIsInRange = startTime.getTime() < startDate.getTime()  && startDate.getTime() < endTime.getTime();
        if (startDateIsInRange) {
          this.startDate = startDate;
        } else {
          this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        }
      } else {
        this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        let endDate = new Date(moment(dateObj.endDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        if (endDate.getTime() > new Date().getTime()) {
          this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        } else {
          this.endDate = endDate;
        }
      }
    }
  };
  /**
   * 获取站点数据
   */
  getPmComData = () => {
    this.correlationService.getPmComData().subscribe(
      result => this.responseUtil.success(result, this.handleComData),
      error => this.responseUtil.error(error)
    )
  };
  handleComData = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.factorDataArr = result.data;
        this.factorDataArr.forEach((val) => {
          val.allChecked = false;
          val.indeterminate = true;
          val.factor.forEach((com, i) => {
            com.checked = i < 1;
          });
        });
      }
      this.updateFactorCheck();
      this.getCorreData();
      this.getCorreLineData();
    } else {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 获取相关性分析数据
   */
  getCorreData() {
    const dataObj = {
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      startTime : this.startDate ? moment(this.startDate).format('YYYY-MM-DD HH:00:00') : '',
      endTime : this.endDate ? moment(this.endDate).format('YYYY-MM-DD HH:00:00') : '',
      factors: this.checkFactorArr.join(',')
    };
    this.correlationService.getCorreData(dataObj).subscribe(
      result => this.responseUtil.success(result, this.handleInodata),
      error => this.responseUtil.error(error)
    );
  }
  handleInodata = (result: MsgResult) => {
    this.isLoading = false;
    this.tableData = [];
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data) {
        this.tableHeadArr = result.data.nameList;
        result.data.rows.forEach((val, i) => {
          this.tableData.push(Object.assign({
            type: this.tableHeadArr[i].name
          }, val))
        });
      }
      this.table.bootstrapTable('refreshOptions', {columns: this.addColumns(), data: this.tableData});
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 获取相关性分析数据
   */
  getCorreLineData() {
    const dataObj = {
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      startTime : this.startDate ? moment(this.startDate).format('YYYY-MM-DD HH:00:00') : '',
      endTime : this.endDate ? moment(this.endDate).format('YYYY-MM-DD HH:00:00') : '',
      factors: this.checkFactorArr.join(',')
    };
    this.correlationService.getCorreLineData(dataObj).subscribe(
      result => this.responseUtil.success(result, this.handleCorreLineData),
      error => this.responseUtil.error(error)
    );
  }
  handleCorreLineData = (result: MsgResult) => {
    this.tableData = [];
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.hasOwnProperty('dataList')) {
        this.chartRender(result.data);
      } else {
        this.chartRender({
          timeList: [],
          nameList: [],
          dataList: []
        });
      }
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 图表
   * @param chartList
   */
  chartRender(chartList) {
    const compareChart = this.chartObj;
    const select = {};
    const nameArr = [];
    if (chartList.nameList && chartList.nameList.length > 0) {
      chartList.nameList.forEach((val, i) => {
        const name = DaFactorName[val] || val;
        nameArr.push(name);
      })
    }
    // 图表配置信息
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: this.formatterChartTooltip
      },
      title: [{
        left: 'center',
        text: DaChartTitle.daCorTitle
      }],
      toolbox: {
        right: '30',
        feature: {
          saveAsImage: {}
        }
      },
      dataZoom: [
        // {
        //   type: 'slider',
        //   show: true,
        //   xAxisIndex: [0]
        // },
        {
          type: 'inside',
          xAxisIndex: [0]
        }
      ],
      legend: {
        bottom: 40,
        left: 'center',
        selected: select,
        width: '90%',
        data: nameArr
      },
      grid: [{
        top: 40,
        bottom: 140
      }],
      color: DaChartColor.color,
      xAxis: [
        {
          type: 'category',
          nameGap: '20',
          // name: '日期',
          nameLocation: 'start',
          boundaryGap: false,
          data: chartList.timeList,
          axisLabel: {
            // rotate: 45,
            color: '#000',
            formatter: (value, index) => {
              // 格式化
              const h = moment(value).format('H:00');
              if (this.timeDataType === 'hourData') {
                return moment(value).format('M月D日 ')  + '\n' + h;
              } else if (this.timeDataType === 'dayData')  {
                return moment(value).format('M月D日 ')
              } else if (this.timeDataType === 'weekData')  {
                return moment(value).format('M月D日')
              } else if (this.timeDataType === 'yearData')  {
                return moment(value).format('YYYY年 ')
              }
            }
          }
        }
      ],
      yAxis: [
        {
          name: 'μg/m³',
          type: 'value',
          splitLine: {
            show: false
          }
        }, {
          name: 'μg/m³',
          type: 'value',
          splitLine: {
            show: false
          }
        }
      ],
      series: [

      ]
    };
    const seriesObj = [];
    chartList.nameList.forEach((name, i) => {
      const dataObj = {
        type: 'line',
        // stack: '总量',
        smooth: true,
        barMaxWidth: 40,
        name: DaFactorName[name] || name,
        data: chartList.dataList[i],
        itemStyle: {
          color: DaFactorColor[chartList.codeList[i]] || DaChartColor.color[i]
        },
        lineStyle: {
          color: DaFactorColor[chartList.codeList[i]] || DaChartColor.color[i]
        }
      };
      if (name === 'PM2_5') {
        Object.assign(dataObj, {yAxisIndex: 1, lineStyle: {color: DaChartColor.PM25Color}, itemStyle: {color: DaChartColor.PM25Color}})
      } else {
        Object.assign(dataObj, {yAxisIndex: 0})
      }
      seriesObj.push(dataObj)
    });
    option.series = seriesObj;
    compareChart.setOption(option, {notMerge: true});
  }
  formatterChartTooltip = (params) => {
    let strRet = '';
    params.forEach((val, i) => {
      let brHtml = '';
      if (i === 0) {
        strRet += '<div>' + params[0].axisValue + '</div>';
      }
      if ((i + 1) % 6 === 0) {
        brHtml = '<br/>';
      }
      strRet += '<div style="display:inline-block;margin-right:6px;">' +
        '<span style="display:inline-block;margin-right:3px;border-radius:10px;width:9px;height:9px;background-color:'
        + params[i].color +
        '";></span>' + val.seriesName + ' : ' + (val.value || ' ') +  '</div>' + brHtml;
    });
    return strRet;
  };
}
